﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using WorkTimePrj.Models;
using WsValid;
using System.Web.BizCode;
using MvcCommon;
using Webdiyer.WebControls.Mvc;
using System.IO;
using WorkTimePrj.Helper;

namespace WorkTimePrj.Controllers
{
    public class AdminController : Controller
    {
        private WorkTimePrjEntities3 db = new WorkTimePrjEntities3();
        private WsFrameDataContext wsdb = new WsFrameDataContext();
        //
        // GET: /Admin/
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ViewResult Index(DateTime? startTime, DateTime? endTime)
        {
            //DateTime startTime;
            //DateTime endTime;
            //string startTimeStr = form["TBStartTime"];
            //string endTimeStr = form["TBEndTime"];
            if (startTime == null)
            {
                int dayOfWeek = (int)DateTime.Today.DayOfWeek;
                if (dayOfWeek == 0)
                {
                    startTime = DateTime.Today.AddDays(-6);
                }
                else
                {
                    startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
                }
            }
            //else
            //    startTime = DateTime.Parse(startTimeStr);
            
            endTime = startTime.Value.AddDays(+6);
            ViewBag.startTime = startTime.Value.ToString("yyyy-MM-dd");
            ViewBag.endTime = endTime.Value.ToString("yyyy-MM-dd");
            //List<vwUserCost> list = db.vwUserCost.Where(i => i.starttime == startTime && i.ack == 1).OrderBy(i => i.DisplayName).ToList();
            List<spGetUserCost_Month_Result> list = db.spGetUserCost_Month(startTime, endTime).OrderBy(i => i.DisplayName).ToList();
            ViewBag.cnt = list.Count();
            ViewBag.action = "";
            //ViewBag.list = list;
            return View(list);
        }

        [HttpPost]
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult Index(FormCollection form, DateTime startTime, DateTime endTime, IEnumerable<spGetUserCost_Result> items)
        {
            string action = form["HAction"];
            string startTime1 = form["TBStartTime"];
            string endTime1 = form["TBEndTime"];
            if (action != "export")
            {
                DateTime startDate = DateTime.Parse(startTime1);
                DateTime endDate = DateTime.Parse(endTime1);
                //DateTime endDate = DateTime.Parse(endTime1).AddDays(-6);
                ViewBag.startTime = startDate;
                ViewBag.endTime = endDate;
                //List<vwUserCost> list = db.vwUserCost.Where(i => i.starttime >= startDate && i.starttime <= endDate && i.ack==1).OrderBy(i=>i.DisplayName).ToList();
                List<spGetUserCost_Month_Result> list = db.spGetUserCost_Month(startDate, endDate).OrderBy(i => i.DisplayName).ToList();
                ViewBag.cnt = list.Count();
                ViewBag.action = "";
                return View(list);
            }
            else
            {
                string attachment = HttpUtility.UrlPathEncode("用户工作量统计" + startTime.ToString() + "-" + endTime.ToString()) + ".xls";
                Dictionary<string, string> head = new Dictionary<string, string>();
                head.Add("Alias", "Name");
                head.Add("姓名", "DisplayName");
                head.Add("角色", "Role");
                head.Add("项目代码", "Code");
                head.Add("项目名称", "Display");
                head.Add("工作量", "TotalCost");

                MemoryStream ms = ExcelHelper.ExportExcel<spGetUserCost_Result>(string.Empty, head, items.ToList());

                return File(ms, "application/vnd.ms-excel", attachment);
            }
        }


        public ActionResult Create()
        {
            return View();
        }

        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ViewResult List()
        {
            DateTime startTime;
            DateTime endTime;
            int dayOfWeek = (int)DateTime.Today.DayOfWeek;
            if (dayOfWeek == 0)
            {
                startTime = DateTime.Today.AddDays(-6);
            }
            else
            {
                startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
            }
            endTime = startTime.AddDays(+6);
            ViewBag.startTime = startTime.ToString("yyyy-MM-dd");
            ViewBag.endTime = endTime.ToString("yyyy-MM-dd");
            List<ProjectCost> list = db.spGetProjectCost_New(startTime, endTime).OrderByDescending(i => i.TotoalCost).ToList();
            ViewBag.cnt = list.Count();
            ViewBag.action = "";
            return View(list);
        }

        [HttpPost]
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult List(FormCollection form, DateTime startTime, DateTime endTime, IEnumerable<ProjectCost> items)
        {
            string startTime1 = form["TBStartTime"];
            string endTime1 = form["TBEndTime"];
            DateTime startDate = DateTime.Parse(startTime1);
            DateTime endDate1 = DateTime.Parse(endTime1);
            DateTime endDate = DateTime.Parse(endTime1).AddDays(-6);
            string action = form["HAction"];
            if (action != "export")
            {
                List<ProjectCost> list = db.spGetProjectCost_New(startDate, endDate).OrderByDescending(i => i.TotoalCost).ToList();
                ViewBag.cnt = list.Count();
                ViewBag.startTime = startDate;
                ViewBag.endTime = endDate1;
                return View(list);
            }
            else
            {

                #region MyRegion

                #region header
                Dictionary<string, string> head = new Dictionary<string, string>();
                head.Add("项目代码", "code");
                head.Add("项目名称", "display");
                head.Add("状态", "status");
                head.Add("PM", "pm");
                head.Add("参与人员", "Members");
                head.Add("售前 Cost", "PresaleCost");
                head.Add("项目经理 Cost", "PMCost");
                head.Add("技术支持 Cost", "TSCost");
                head.Add("美工 Cost", "ARTCost");
                head.Add("开发 Cost", "DEVCost");
                head.Add("测试 Cost", "TESTERCost");
                head.Add("合计", "TotoalCost");

                #endregion

                //Write the stream data of workbook to the root directory
                MemoryStream file = ExcelHelper.ExportExcel<ProjectCost>(string.Empty, head, items.ToList());

                return File(file, "application/vnd.ms-excel", HttpUtility.UrlPathEncode("项目工作量统计" + startTime.ToString("yyyy-MM-dd") + "-" + endTime.ToString("yyyy-MM-dd")) + ".xls");
                #endregion
            }
        }

        public ActionResult Email(string msg)
        {
            if (msg != null)
                this.ShowMessage(msg);
            return View();
        }

        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult Email1()
        {
            int dayOfWeek = (int)DateTime.Today.DayOfWeek;
            DateTime startTime;
            if (dayOfWeek == 0)
            {
                startTime = DateTime.Today.AddDays(-6);
            }
            else
            {
                startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
            }
            DateTime startTime1 = startTime.AddDays(+7);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<div style='font-size:14px;color:#0000ff'>Dear all,<br/>");
            sb.Append("请大家尽快登录http://wsgpd/ 补登记或修正" + startTime.ToString("yyyy年MM月dd日") + "起至今自己在各项目上投入的工作量，本次补登记工作的截止日期为" + startTime1.ToString("yyyy年MM月dd日") + "（周一）。<br/>");
            sb.Append("不在公司内的同事，可用自己的域账号登录以下地址进行操作：");
            sb.Append("http://www.wsgpd.com/</div>");
            try
            {
                WorkTimePrj.wsweb.Service1 s = new wsweb.Service1();
                string userName = System.Configuration.ConfigurationManager.AppSettings["UserName"].ToString();
                string encry_pass = System.Configuration.ConfigurationManager.AppSettings["Pass"].ToString();
                string decry_pass = Encrypt.DESDecrypt(encry_pass, "12345678");
                s.Credentials = new System.Net.NetworkCredential(userName, decry_pass, "Wicresoft");
                s.SendMailAsync("hhchen", "veronr;", null, null, "上周工作量登记", sb.ToString());
                //ViewBag.msg1 = "邮件发送成功";
                return RedirectToAction("Email", new { msg = "邮件发送成功！" });
            }
            catch
            {
                //ViewBag.msg1 = "邮件发送失败";
                //this.ShowMessage("邮件发送失败！");
                return RedirectToAction("Email", new { msg = "邮件发送失败！" });
            }
        }

        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult Email2()
        {
            int dayOfWeek = (int)DateTime.Today.DayOfWeek;
            DateTime startTime;
            if (dayOfWeek == 0)
            {
                startTime = DateTime.Today.AddDays(-6);
            }
            else
            {
                startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
            }
            DateTime startTime1 = startTime.AddDays(+7);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<div style='font-size:14px;color:#0000ff'>Dear all,<br/>");
            sb.Append("请大家尽快登录http://wsgpd/ 确认" + startTime.ToString("yyyy年MM月dd日") + "起至今的项目投入，截止日期为" + startTime1.ToString("yyyy年MM月dd日") + "（周一）。<br/>");
            sb.Append("不在公司内的同事，可用自己的域账号登录以下地址进行操作：");
            sb.Append("http://www.wsgpd.com/</div>");
            try
            {
                WorkTimePrj.wsweb.Service1 s = new wsweb.Service1();
                string userName = System.Configuration.ConfigurationManager.AppSettings["UserName"].ToString();
                string encry_pass = System.Configuration.ConfigurationManager.AppSettings["Pass"].ToString();
                string decry_pass = Encrypt.DESDecrypt(encry_pass, "12345678");
                s.Credentials = new System.Net.NetworkCredential(userName, decry_pass, "Wicresoft");
                s.SendMailAsync("hhchen", "veronr;hhchen", null, null, "上周项目投入确认", sb.ToString());
                return RedirectToAction("Email", new { msg = "邮件发送成功！" });
                //ViewBag.msg2 = "邮件发送成功";
                //this.ShowMessage("邮件发送成功！");
            }
            catch
            {
                //ViewBag.msg2 = "邮件发送失败";
                //this.ShowMessage("邮件发送失败！");
                return RedirectToAction("Email", new { msg = "邮件发送失败！" });
            }


        }

        public ActionResult Manage(string msg)
        {
            string rolenames = "";
            List<Guid> roles = wsdb.Relation.Where(l => l.ChildNodeID == Consts.CurrentUser.ID && l.Type == 1001).Select(s => s.ParentNodeID).ToList();
            foreach (Guid item in roles)
            {
                if (item == new Guid("db02cf61-1743-4248-b756-b4fde23af7fa"))
                    rolenames += "ART;";
                if (item == new Guid("9bcd6465-d530-4d0a-915c-eec1e7b765b1"))
                    rolenames += "DEV;";
                if (item == new Guid("60012941-1306-48b7-b829-f71934780c90"))
                    rolenames += "PM;";
                if (item == new Guid("bf55634d-851c-4a41-b10d-2aee7cd03d30"))
                    rolenames += "PRESALES;";
                if (item == new Guid("f0ac1a56-b8ef-404b-8ebb-07687671e141"))
                    rolenames += "TESTER;";
                if (item == new Guid("2ac26434-d4be-4b0b-9996-46c996fc6a8b"))
                    rolenames += "TS;";
                if (item == new Guid("BA144991-0307-4A52-B6E8-CA7B8FC3B5B9"))
                    rolenames += "ProjMgmt;";
            }


            ViewBag.roles = rolenames;
            //this.ShowMessage(roles);
            return View();
        }

        public ActionResult Excel(List<spGetUserCost_Month_Result> list)
        {
            //List<spGetUserCost_Result> list1 = (List<spGetUserCost_Result>)list;
            string attachment = "attachment; filename=" + HttpUtility.UrlPathEncode("用户工作量统计") + ".xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            Response.Charset = "gb2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            string tab = "";
            Response.Write(tab + "Alias");
            tab = "\t";
            Response.Write(tab + "姓名");
            tab = "\t";
            Response.Write(tab + "角色");
            tab = "\t";
            Response.Write(tab + "项目代码");
            tab = "\t";
            Response.Write(tab + "项目名称");
            tab = "\t";
            Response.Write(tab + "工作量");
            Response.Write("\n");
            foreach (spGetUserCost_Month_Result item in list)
            {
                tab = "";
                Response.Write(tab + item.Name);
                tab = "\t";
                Response.Write(tab + item.DisplayName);
                tab = "\t";
                Response.Write(tab + item.Role);
                tab = "\t";
                Response.Write(tab + item.Code);
                tab = "\t";
                Response.Write(tab + item.Display);
                tab = "\t";
                Response.Write(tab + item.TotalCost);
                Response.Write("\n");
            }
            Response.End();
            Response.Write("");
            return RedirectToAction("Index", "Admin", new { startTime = ViewBag.startTime, endTime = ViewBag.endTime });
        }
        //[WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        //public ViewResult ListUser(IEnumerable<Item> list)
        //{
        //    return View(list);
        //}
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ViewResult ListUser(string account, Guid? pid, DateTime? startTime, DateTime? endTime)
        {
            DateTime defaultTime = DateTime.Parse("1900-1-1 0:0:0");
            DateTime startDate = startTime.HasValue ? startTime.Value : defaultTime;
            DateTime endDate = endTime.HasValue ? endTime.Value.AddDays(-6) : defaultTime;
            Guid _pid = pid.HasValue ? pid.Value : Guid.Empty;
            ViewBag.startTime = startTime;
            ViewBag.endTime = endTime;
            ViewBag.userSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName", account);
            ViewBag.projectSelectList = new SelectList(db.Project.OrderBy(e => e.code), "pid", "display", pid);
            List<Item> items = (from u in db.Item
                                where (account == "" || (account != string.Empty && u.account == account))
                                && (_pid == Guid.Empty || (_pid != Guid.Empty && u.pid == _pid))
                                && (startDate == defaultTime || (startDate != defaultTime && u.starttime >= startDate))
                                && (endDate == defaultTime || (endDate != defaultTime && u.starttime <= endDate))
                                select u).ToList();

            ViewBag.cnt = items.Count();
            ViewBag.account = account;
            return View(items);
        }
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ViewResult ListProject(string account, Guid? pid, DateTime? startTime, DateTime? endTime)
        {
            DateTime defaultTime = DateTime.Parse("1900-1-1 0:0:0");
            DateTime startDate = startTime.HasValue ? startTime.Value : defaultTime;
            DateTime endDate = endTime.HasValue ? endTime.Value.AddDays(-6) : defaultTime;
            Guid _pid = pid.HasValue ? pid.Value : Guid.Empty;
            ViewBag.startTime = startTime;
            ViewBag.endTime = endTime;
            ViewBag.userSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName", account);
            ViewBag.projectSelectList = new SelectList(db.Project.OrderBy("it.status desc, it.display"), "pid", "code_display_status", pid);
            List<Item> items = (from u in db.Item
                                where (account == "" || (account != string.Empty && u.account == account))
                                && (_pid == Guid.Empty || (_pid != Guid.Empty && u.pid == _pid))
                                && (startDate == defaultTime || (startDate != defaultTime && u.starttime >= startDate))
                                && (endDate == defaultTime || (endDate != defaultTime && u.starttime <= endDate))
                                select u).ToList();

            ViewBag.cnt = items.Count();
            return View(items);
        }
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ViewResult AddVacOT(int? refresh, DateTime? startTime = null, DateTime? endTime = null)
        {
            if (startTime == null || endTime == null || (endTime.Value - startTime.Value).Days >= 7)
            {
                int dayOfWeek = (int)DateTime.Today.DayOfWeek;
                if (dayOfWeek == 0)
                {
                    startTime = DateTime.Today.AddDays(-6);
                }
                else
                {
                    startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
                }
                endTime = startTime.Value.AddDays(+6);
            }
            ViewBag.startTime = startTime;
            ViewBag.endTime = endTime;
            Vac_OT voc = new Vac_OT();
            voc.startDate = startTime.Value;
            voc.endDate = endTime;

            voc.accountlist = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName");
            voc.typelist = new SelectList(db.Vac_OT_Type.OrderBy(e => e.ID), "ID", "Type");
            ViewBag.refresh = refresh;
            
            return View(voc);
        }
        [HttpPost]
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult AddVacOT(Vac_OT vot, DateTime startTime, DateTime endTime)
        {
            if (ModelState.IsValid)
            {
                db.Vac_OT.AddObject(vot);
                vot.startDate = startTime;
                vot.endDate = endTime;
                vot.addUser = Consts.CurrentUser.Name;
                vot.addTime = DateTime.Now;
                ViewBag.refresh = 1;
                db.SaveChanges();
                this.ShowMessage("保存成功");
                return RedirectToAction("AddVacOT", new { refresh = 1, startTime = startTime, endTime = endTime });
                //return RedirectToAction("Index");
                //this.CloseWindow();
            }
            else
            {
                vot.accountlist = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName", vot.account);
                vot.typelist = new SelectList(db.Vac_OT_Type.OrderBy(e => e.ID), "ID", "Type", vot.type);
                ViewBag.startTime = startTime;
                ViewBag.endTime = endTime;
                return View(vot);
            }

        }
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ViewResult VOTList(string orderBy, int? id, DateTime? startTime, DateTime? endTime)
        {
            if (startTime == null || endTime == null || (endTime.Value - startTime.Value).Days >= 7)
            {
                int dayOfWeek = (int)DateTime.Today.DayOfWeek;
                if (dayOfWeek == 0)
                {
                    startTime = DateTime.Today.AddDays(-6);
                }
                else
                {
                    startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
                }
                endTime = startTime.Value.AddDays(+6);
            }
            ViewBag.startTime = startTime;
            ViewBag.endTime = endTime;
            ViewBag.cnt = db.vwVOT.Count(e => e.startDate == startTime);
            PagedList<vwVOT> votList;
            if (orderBy == "" || orderBy == null)
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else if (orderBy == "DisplayName asc")
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderBy(e => e.DisplayName).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else if (orderBy == "DisplayName desc")
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderByDescending(e => e.DisplayName).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else if (orderBy == "hour asc")
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderBy(e => e.hour).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else if (orderBy == "hour desc")
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderByDescending(e => e.hour).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else if (orderBy == "addUser asc")
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderBy(e => e.addUser).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else if (orderBy == "addUser desc")
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderByDescending(e => e.addUser).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else if (orderBy == "addTime asc")
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderBy(e => e.addTime).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else if (orderBy == "addTime desc")
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderByDescending(e => e.addTime).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else if (orderBy == "Type asc")
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderBy(e => e.Type).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);
            else
                votList = db.vwVOT.Where(e => e.startDate == startTime).OrderByDescending(e => e.Type).ThenBy(e => e.DisplayName).ToPagedList(id ?? 1, 10);

            int i = 1; ;
            //if (id == null || id == 1)
            //    i = 1;
            //else
            //    i = (id - 1).Value * 3 + 1;
            foreach (vwVOT item in votList)
            {
                item.Num = i;
                i++;
            }
           
            if (id == null)
                ViewBag.pagenum = 1;
            else
                ViewBag.pagenum = id;
            return View(votList);
           
        }
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ViewResult EditVOT(int id)
        {
            Vac_OT vot = db.Vac_OT.Single(x => x.ID == id);
            vot.accountlist = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName", vot.account);
            vot.typelist = new SelectList(db.Vac_OT_Type.OrderBy(e => e.ID), "ID", "Type", vot.type);
            return View(vot);
        }
        [HttpPost]
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult EditVOT(Vac_OT vot)
        {
            if (ModelState.IsValid)
            {
                db.Vac_OT.Attach(vot);
                db.ObjectStateManager.ChangeObjectState(vot, EntityState.Modified);
                db.SaveChanges();
                vot.accountlist = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName", vot.account);
                vot.typelist = new SelectList(db.Vac_OT_Type.OrderBy(e => e.ID), "ID", "Type", vot.type);
                this.ShowMessage("保存成功");
                //this.CloseWindow();
                ViewBag.close = 1;
                return View(vot);
                //return View("Close");
            }
            else
            {
                vot.accountlist = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName", vot.account);
                vot.typelist = new SelectList(db.Vac_OT_Type.OrderBy(e => e.ID), "ID", "Type", vot.type);
                return View(vot);
            }
        }
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ViewResult DetailVOT(int id)
        {
            vwVOT vot = db.vwVOT.SingleOrDefault(x => x.ID == id);
            //vot.accountlist = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName", vot.account);
            //vot.typelist = new SelectList(db.Vac_OT_Type.OrderBy(e => e.ID), "ID", "Type", vot.type);
            return View(vot);
        }

        [AcceptVerbs(HttpVerbs.Delete)]
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult DelVOT(int id)
        {
            Vac_OT vot = db.Vac_OT.Single(x => x.ID == id);
            db.Vac_OT.DeleteObject(vot);
            //ViewBag.refresh = 1;
            //this.ShowMessage("删除成功");
            db.SaveChanges();
            return Json(new { msg = "1" });
        }
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult ExportVOT(int pagenum, DateTime startTime, DateTime endTime)
        {
            List<vwVOT> votList = db.vwVOT.Where(e => e.startDate == startTime).OrderByDescending(e => e.DisplayName).ToList();
            string attachment = HttpUtility.UrlPathEncode("休假、加班统计" + startTime.ToString("yyyy年MM月dd日") + "至" + endTime.ToString("yyyy年MM月dd日")) + ".xls";
            Dictionary<string, string> head = new Dictionary<string, string>();
            //head.Add("统计时间");

            //head.Add(startTime.ToString("yyyy-MM-dd") + "至" + endTime.ToString("yyyy-MM-dd"),"DisplayName");
            head.Add("姓名", "DisplayName");
            head.Add("类型", "Type");
            head.Add("时长", "hour");
            head.Add("添加用户", "addUser");
            head.Add("添加时间", "addTime");

            MemoryStream ms = ExcelHelper.ExportExcel<vwVOT>("统计时间 " + startTime.ToString("yyyy-MM-dd") + "至" + endTime.ToString("yyyy-MM-dd"), head, votList);

            return File(ms, "application/vnd.ms-excel", attachment);
            //return View(db.Project.ToList());
        }
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult VOTPartialView(string account, DateTime? startTime, DateTime? endTime)
        {
            endTime = endTime.Value.AddDays(-6);
            List<spUserWorkTime_VOC_Result> list = db.spUserWorkTime_VOC(startTime, endTime, account).ToList();
            spUserWorkTime_VOC_Result ret = list[0];
            ViewBag.TotalCost = ret.TotalCost;
            ViewBag.OTCost = ret.OTCost;
            ViewBag.VACCost = ret.VACCost;
            ViewBag.WorkCost = ret.workcost;
            return PartialView();
        }
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult WorkVOT(DateTime? startTime, DateTime? endTime)
        {
            if (startTime == null)
            {
                int dayOfWeek = (int)DateTime.Today.DayOfWeek;
                if (dayOfWeek == 0)
                {
                    startTime = DateTime.Today.AddDays(-6);
                }
                else
                {
                    startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
                }
                endTime = startTime;
            }
            else
                endTime = endTime.Value.AddDays(-6);
            DateTime endTime1 = startTime.Value.AddDays(+6);
            ViewBag.startTime = startTime.Value.ToString("yyyy-MM-dd");
            ViewBag.endTime = endTime1.ToString("yyyy-MM-dd");
            List<spUserWorkTime_VOC_Result> list = db.spUserWorkTime_VOC(startTime, endTime, "").OrderBy(i => i.DisplayName).ToList();
            ViewBag.cnt = list.Count();
            return View(list);
        }
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        [HttpPost]
        public ActionResult WorkVOT(FormCollection form, IEnumerable<spUserWorkTime_VOC_Result> items)
        {
            string action = form["HAction"];
            string startTime1 = form["TBStartTime"];
            string endTime1 = form["TBEndTime"];
            DateTime startDate = DateTime.Parse(startTime1);
            DateTime endDate = DateTime.Parse(endTime1);
            DateTime endDate1 = DateTime.Parse(endTime1).AddDays(-6);
            if (action != "export")
            {
                List<spUserWorkTime_VOC_Result> list = db.spUserWorkTime_VOC(startDate, endDate1, "").OrderBy(i => i.DisplayName).ToList();
                ViewBag.startTime = startDate.ToString("yyyy-MM-dd");
                ViewBag.endTime = endDate.ToString("yyyy-MM-dd");
                ViewBag.cnt = list.Count();
                ViewBag.action = "";
                return View(list);
            }
            else
            {
                string attachment = HttpUtility.UrlPathEncode("用户工作量休假统计" + startDate.ToString("yyyy-MM-dd") + "-" + endDate.ToString("yyyy-MM-dd")) + ".xls";


                #region MyRegion

                Dictionary<string, string> head = new Dictionary<string, string>();
                head.Add("Alias", "Name");

                head.Add("姓名", "DisplayName");

                head.Add("角色", "Role");

                head.Add("实际工作量（小时）", "TotalCost");

                head.Add("加班（小时）", "OTCost");

                head.Add("请假（小时）", "VACCost");

                head.Add("出勤总数（小时）", "workcost");

                MemoryStream ms = ExcelHelper.ExportExcel<spUserWorkTime_VOC_Result>(string.Empty, head, items.ToList());
                return File(ms, "application/vnd.ms-excel", attachment);
                #endregion

            }
        }
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ViewResult AddVacOT_New(DateTime? startTime = null)
        {
            if (startTime == null)
            {
                startTime = DateTime.Now;
            }
            VAC_OT_New vac_ot = new VAC_OT_New();
            List<spVACTotalByYear_Result> list = db.spVACTotalByYear(Consts.CurrentUser.Name).ToList();
            spVACTotalByYear_Result ret = list[0];
            ViewBag.TotalALAmount = ret.total_al_amount.Value;
            ViewBag.TotalSickLeaveAmount = ret.total_sick_leave_amount.Value;
            ViewBag.UsedALAmount = ret.TotalALAmount.Value;
            ViewBag.UsedSickLeaveAmount = ret.TotalSickLeaveAmount.Value;
            ViewBag.RemainingALAmount = ret.RemainingALAmount.Value;
            ViewBag.RemainingSickLeaveAmount = ret.RemainingSickLeaveAmount.Value;
            ViewBag.adduser = Consts.CurrentUser.DisplayName;
            ViewBag.startTime = startTime.Value.ToString("yyyy-MM-dd");
            ViewBag.accSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName", Consts.CurrentUser.Name);
            ViewBag.typeSelectList = new SelectList(new String[] { "年假", "病假", "外出" });
            ViewBag.hourSelectList = new SelectList(new String[] { "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00" });
            return View();
        }
        [HttpPost]
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult AddVacOT_New(VAC_OT_New vac_ot)
        {
            if (ModelState.IsValid)
            {
                vac_ot.addUser = Consts.CurrentUser.Name;
                vac_ot.addTime = DateTime.Now;
                db.VAC_OT_New.AddObject(vac_ot);
                db.SaveChanges();
                //SendEmail(vac_ot);
                this.ShowMessage("保存成功");
                return RedirectToAction("AddVacOT_New");
            }
            else
            {
                ViewBag.adduser = Consts.CurrentUser.DisplayName;
                ViewBag.startTime = vac_ot.startDate.Value.ToString("yyyy-MM-dd");
                ViewBag.accSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName");
                ViewBag.typeSelectList = new SelectList(new String[] { "年假", "病假", "外出" });
                ViewBag.hourSelectList = new SelectList(new String[] { "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00" });
                return View(vac_ot);
            }

        }
        [HttpPost]
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult GetUserVACAmount(string account)
        {
            List<spVACTotalByYear_Result> list = db.spVACTotalByYear(account).ToList();
            spVACTotalByYear_Result ret = list[0];
            int TotalALAmount = ret.total_al_amount.Value;
            int TotalSickLeaveAmount = ret.total_sick_leave_amount.Value;
            int UsedALAmount = ret.TotalALAmount.Value;
            int UsedSickLeaveAmount = ret.TotalSickLeaveAmount.Value;
            int RemainingALAmount = ret.RemainingALAmount.Value;
            int RemainingSickLeaveAmount = ret.RemainingSickLeaveAmount.Value;
            List<WorkTimePrj.Models.User> list1 = db.User.Where("it.Name='" + account + "'").ToList();
            WorkTimePrj.Models.User user = list1[0];
            string DisplayName = user.DisplayName;

            return Json(new { DisplayName = DisplayName, TotalALAmount = TotalALAmount, TotalSickLeaveAmount = TotalSickLeaveAmount, UsedALAmount = UsedALAmount, UsedSickLeaveAmount = UsedSickLeaveAmount, RemainingALAmount = RemainingALAmount, RemainingSickLeaveAmount = RemainingSickLeaveAmount });
        }
        private bool SendEmail(VAC_OT_New vac_ot)
        {
            string account = vac_ot.account;
            List<WorkTimePrj.Models.User> list1 = db.User.Where("it.Name='" + account + "'").ToList();
            string displayname = list1[0].DisplayName;
            string adduser = vac_ot.addUser;
            List<WorkTimePrj.Models.User> list2 = db.User.Where("it.Name='" + adduser + "'").ToList();
            adduser = list2[0].DisplayName;
            string addtime = vac_ot.addTime.Value.ToString("yyyy-MM-dd");
            string startdate = vac_ot.startDate.Value.ToString("yyyy-MM-dd");
            string type = vac_ot.type;
            string hour = vac_ot.hour.ToString();
            string cause = vac_ot.Cause;
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<div style='font-size:12px;color:#0000ff'>" + displayname + "申请" + type + hour + "小时<br/>");
            sb.Append("申请人&nbsp;" + displayname + "<br/>");
            sb.Append("开始时间&nbsp;" + startdate + "<br/>");
            sb.Append("类型&nbsp;" + type + "<br/>");
            sb.Append("时长&nbsp;" + hour + "<br/>");
            sb.Append("事由&nbsp;" + cause + "<br/>");
            sb.Append("登记用户&nbsp;" + adduser + "<br/>");
            sb.Append("登记时间&nbsp;" + addtime + "<br/>");
            sb.Append("</div>");
            try
            {
                WorkTimePrj.wsweb.Service1 s = new wsweb.Service1();
                string userName = System.Configuration.ConfigurationManager.AppSettings["UserName"].ToString();
                string encry_pass = System.Configuration.ConfigurationManager.AppSettings["Pass"].ToString();
                string decry_pass = Encrypt.DESDecrypt(encry_pass, "12345678");
                s.Credentials = new System.Net.NetworkCredential(userName, decry_pass, "Wicresoft");
                s.SendMailAsync("sherry", "wsdall", null, null, "请假申请", sb.ToString());
                return true;
            }
            catch
            {
                return false;
            }
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            wsdb.Dispose();
            base.Dispose(disposing);
        }
    }
}